package org.mspring.platform.web.freemarker.widget.render.impl;

import java.io.IOException;

import javax.servlet.ServletException;

import org.mspring.platform.cache.CacheManager;
import org.mspring.platform.web.freemarker.widget.WidgetNotFoundException;
import org.mspring.platform.web.freemarker.widget.config.WidgetConfig;
import org.mspring.platform.web.freemarker.widget.http.HttpWidget;
import org.mspring.platform.web.freemarker.widget.http.HttpWidgetRequest;
import org.mspring.platform.web.freemarker.widget.http.HttpWidgetResponse;
import org.mspring.platform.web.freemarker.widget.render.AbstractWidgetRender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Gao Youbo
 * @since 2012-12-5
 */
public class StandardWidgetRender extends AbstractWidgetRender {

    private static final Logger log = LoggerFactory.getLogger(StandardWidgetRender.class);

    @Override
    protected void nativeWidgetRender(WidgetConfig widgetConfig, CacheManager cacheManager, HttpWidgetRequest widgetRequest, HttpWidgetResponse widgetResponse) {

        if (widgetConfig == null) {
            return;
        }

        HttpWidget widget = getHttpWidgetCache(widgetConfig, cacheManager, widgetRequest, widgetResponse);
        if (widget != null) {
            return;
        }

        try {
            String path = widgetConfig.getPath();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(path)) {
                try {
                    widgetRequest.getRequestDispatcher(path).include(widgetRequest, widgetResponse);
                } catch (IOException | ServletException e) {
                    log.error(e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            throw new WidgetNotFoundException("widget render exception!", e);
        }
    }
}
